<template>
  <el-dialog
    v-model="dialogVisible"
    title="意见反馈"
    width="560px"
    :close-on-click-modal="false"
    class="feedback-dialog"
  >
    <!-- 新增tabs切换 -->
    <el-tabs v-model="activeTab" class="feedback-tabs" @tab-click="handleTabClick">
      <el-tab-pane label="我要反馈" name="feedback"></el-tab-pane>
      <el-tab-pane label="反馈历史" name="history"></el-tab-pane>
    </el-tabs>

    <template v-if="activeTab === 'feedback'">
      <el-form
        :model="feedbackForm"
        :rules="rules"
        ref="feedbackFormRef"
        label-width="80px"
        class="feedback-form"
      >
        <!-- 反馈类型 -->
        <el-form-item label="反馈类型" prop="type">
          <el-radio-group v-model="feedbackForm.type" class="type-group">
            <el-radio label="suggestion">建议</el-radio>
            <el-radio label="bug">bug反馈</el-radio>
            <el-radio label="complaint">投诉</el-radio>
            <el-radio label="question">其他问题</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 反馈内容 -->
        <el-form-item label="反馈内容" prop="content">
          <el-input
            v-model="feedbackForm.content"
            type="textarea"
            :rows="6"
            placeholder="请详细描述您的问题（最多500字）"
            maxlength="500"
            show-word-limit
            class="content-area"
          />
        </el-form-item>

        <!-- 联系方式 -->
        <el-form-item label="联系方式" prop="contact">
          <el-input
            v-model="feedbackForm.contact"
            placeholder="选填：手机号/邮箱"
            maxlength="100"
            class="contact-input"
          />
        </el-form-item>
      </el-form>
    </template>

    <!-- 反馈历史面板 -->
    <template v-else>
      <div class="history-list">
        <div
          class="history-item"
          v-for="(item, index) in historyData"
          :key="index"
        >
          <div class="item-header">
            <!-- <span class="item-number">{{ index+1}}.</span> -->
            <span class="item-time">反馈的时间：{{ item.create_time }}</span>
          </div>
          <div class="item-content">反馈内容：{{ item.content }}</div>
          <div class="item-reply" v-if="item.response">
            <span class="reply-label">管理员回复：</span>{{ item.response }}
          </div>
          <!-- !-- 新增展开详情部分  -->
          <div class="item-details" v-if="expandedItems[index]">
            <div class="detail-row">
              <span class="detail-label">反馈类型：</span>
              <span class="detail-value">{{ getTypeName(item.type) }}</span>
            </div>
            <div class="detail-row" v-if="item.contact">
              <span class="detail-label">联系方式：</span>
              <span class="detail-value">{{ item.contact }}</span>
            </div>
            <div class="detail-row" v-if="item.response">
              <span class="detail-label">管理员恢复：</span>
              <span class="detail-value">{{ item.response }}</span>
            </div>
            <div class="detail-row">
              <span class="detail-label">处理状态：</span>
              <span class="detail-value">{{ getStatusName(item.status) }}</span>
            </div>
          </div>

          <div class="item-footer">
            <el-button
              type="text"
              @click="toggleDetails(index)"
              class="toggle-details-btn"
            >
              {{ expandedItems[index] ? '收起详情' : '查看更多' }}
            </el-button>
          </div>
        </div>
        <div class="empty-tip" v-if="historyData.length === 0">
          暂无反馈历史记录
        </div>
      </div>
    </template>

    <template #footer>
      <el-button
        v-if="activeTab === 'feedback'"
        @click="dialogVisible = false"
        class="cancel-btn"
      >取消</el-button>
      <el-button
        v-if="activeTab === 'feedback'"
        type="primary"
        @click="submitFeedback"
        :loading="submitting"
        class="submit-btn"
      >
        提交
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElDialog, ElForm, ElFormItem, ElRadioGroup, ElRadio, ElInput, ElTabs, ElTabPane, ElButton } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const dialogVisible = ref(false)
const feedbackFormRef = ref()
const submitting = ref(false)
const activeTab = ref('feedback') // 新增tabs切换
// 新增展开状态管理
const expandedItems = ref({})


const historyData =ref([])

const feedbackForm = reactive({
  type: 'suggestion',
  content: '',
  contact: ''
})

const rules = {
  type: [{ required: true, message: '请选择反馈类型', trigger: 'change' }],
  content: [
    { required: true, message: '请输入反馈内容', trigger: 'blur' },
    { min: 10, message: '反馈内容至少10个字符', trigger: 'blur' }
  ],
  contact: [
    {
      // pattern: /^(\w+@\w+\.\w+|1[3-9]\d{9}|)$/,
      message: '请输入有效的邮箱或手机号',
      trigger: 'blur'
    }
  ]
}

// 处理tab切换
const handleTabClick = (tab) => {
  activeTab.value = tab.name
}

const formatDateTime = (date) => {
  const pad = num => String(num).padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
const submitFeedback = async () => {
  try {
    await feedbackFormRef.value.validate()
    submitting.value = true

    // 构建请求数据
    const feedbackData = {
      user_id: localStorage.getItem('id'),
      type: feedbackForm.type,
      content: feedbackForm.content,
      contact: feedbackForm.contact || '',
      status: 'pending',
      create_time: formatDateTime(new Date())
    }

    console.log(feedbackData);

    const response = await axios.post('/api/feekback/addFeekback',feedbackData )


    if (response.data.code === 200) {
      ElMessage.success('反馈提交成功')
      dialogVisible.value = false
      feedbackFormRef.value.resetFields()
      feedbackForm.type = 'suggestion'
      // 可调用接口刷新反馈历史
    } else {
      ElMessage.error(response.data.msg || '反馈提交失败')
    }
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data?.msg || '服务器错误')
    } else if (error.request) {
      ElMessage.error('网络错误，请检查连接')
    } else {
      ElMessage.error('请求配置错误: ' + error.message)
    }
    console.error('反馈提交错误:', error)
  } finally {
    submitting.value = false
  }
}

const openDialog = () => {
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    return
  }
  dialogVisible.value = true
}

defineExpose({ openDialog })

onMounted(() => {
  // 可在此处调用接口获取真实反馈历史
  fetchHistory()
})

// 获取反馈历史
const fetchHistory = async () => {
  const res = await axios.get('/api/feekback/getByUserId', {
    params: { user_id: localStorage.getItem('id') }
  })
  if (res.data.code === 200) {
    historyData.value = res.data.data
    // console.log(res.data.data);

  }
}
// 切换详情展开状态
const toggleDetails = (index) => {
  expandedItems.value = {
    ...expandedItems.value,
    [index]: !expandedItems.value[index]
  }
}

// 反馈类型映射
const getTypeName = (type) => {
  const typeMap = {
    suggestion: '建议',
    bug: 'BUG反馈',
    complaint: '投诉',
    question: '其他问题'
  }
  return typeMap[type] || type
}

// 状态映射
const getStatusName = (status) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    resolved: '已解决',
    rejected: '已拒绝'
  }
  return statusMap[status] || status
}
</script>

<style scoped>
/* 弹窗整体样式 */
.feedback-dialog {
  --el-dialog-header-text-color: #333;
  --el-dialog-background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.12);
}

/* Tabs切换栏 */
.feedback-tabs {
  margin: 10px 0 20px;
  border-bottom: 1px solid #eee;
}
.feedback-tabs .el-tabs__item {
  color: #666;
  font-size: 16px;
  padding: 0 20px 12px;
}
.feedback-tabs .el-tabs__item.is-active {
  color: #f85959;
  border-bottom: 2px solid #f85959;
}

/* 表单基础样式 */
.feedback-form {
  padding: 0 20px;
}

/* 反馈类型 */
.type-group {
  display: flex;
  gap: 24px;
}
.type-group .el-radio {
  font-size: 14px;
  color: #666;
}

/* 反馈内容输入框 */
.content-area {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
}

/* 联系方式输入框 */
.contact-input {
  font-size: 14px;
  color: #333;
}

/* 反馈历史 */
.history-list {
  padding: 0 20px;
}
.history-item {
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
}
.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  gap: 8px;
}
.item-type {
  padding: 4px 8px;
  border-radius: 4px;
  color: #fff;
  font-size: 12px;
}
.type-suggestion { background-color: #409eff; }
.type-bug { background-color: #f90; }
.type-complaint { background-color: #f56c6c; }
.type-other { background-color: #909399; }
.item-time {
  font-size: 12px;
  color: #999;
}
.item-content {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
  margin-bottom: 8px;
}
.item-reply {
  font-size: 14px;
  color: #666;
}
.empty-tip {
  text-align: center;
  color: #999;
  padding: 20px 0;
}

/* 按钮样式 */
.cancel-btn {
  color: #666;
  border-color: #ddd;
}
.cancel-btn:hover {
  background-color: #f8f8f8;
  border-color: #ccc;
}
.submit-btn {
  background-color: #f85959;
  border-color: #f85959;
}
.submit-btn:hover {
  background-color: #ff7070;
  border-color: #ff7070;
}
.item-number {
  /* margin-right: 8px; */
  font-weight: normal;
  color: #666;
}
/* 详情展开区域样式 */
.item-details {
  margin-top: 12px;
  padding: 12px;
  background-color: #f9f9f9;
  border-radius: 4px;
  font-size: 13px;
}

.detail-row {
  margin-bottom: 8px;
  display: flex;
}

.detail-label {
  color: #666;
  min-width: 70px;
}

.detail-value {
  color: #333;
  flex: 1;
}

.item-footer {
  margin-top: 8px;
  text-align: right;
}

.toggle-details-btn {
  padding: 0;
  font-size: 12px;
  color: #f85959;
}

.toggle-details-btn:hover {
  color: #ff7070;
}
</style>
